﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using System.Configuration;
using Estimate.Common;
using Estimate.Common.Repository;
using Estimate.Common.DataFileFinder;
using Estimate.Common.DataFileCopyer;
using Estimate.Common.Estimate;
using Estimate.Common.Entity;
using Estimate.Common.DBFieldTypes;
using Estimate.Common.Memcached;
using Estimate.Common.DBHealth;
using Estimate.Common.OldEstimate;
using System.Data.SqlClient;
using log4net;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace ManuaOperateTool
{
    class Program
    {
        public static ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        static void Main(string[] args)
        {
            
            //reimportCityFore(new DateTime(2012, 4, 25), new DateTime(2012, 4, 25));
            //reimportZytFore(new DateTime(2013, 5, 1), new DateTime(2013, 5, 1));
            
            //reCalculateSemi(new DateTime(2012, 1, 1), new DateTime(2012, 1, 7));

            /*
            DateTime time1 = new DateTime(2012, 5, 25);
            ForeRepository repository1 = ForeRepositoryFactory.NormalCityForeRepository(ConfigurationManager.AppSettings["ConnectionString"]);
            BaseForeHealth health1 = new CityForeHealth(repository1);
            CheckForeRepositoryHealth(health1, time1, time1);
            */

            //CompareSemi("site", ForeSemiType.Auto, new DateTime(2013, 5, 31), new DateTime(2013, 5, 31));
            //return;
            //reCalculateSemi(new DateTime(2013, 5,31), new DateTime(2013, 5, 31));
            //return;
            if (args.Length == 0)
            {
                printMenu();
                return;
            }
            DataImporterCombiner combiner = new DataImporterCombiner(ConfigurationManager.AppSettings);
            
            switch (args[0])
            {
                #region import 导入某一天的数据
                case "import":
                    if (args.Length == 2)
                    {
                        DateTime time;
                        try
                        {
                            time = DateTime.Parse(args[1]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }
                        try
                        {
                            combiner.execute(time);
                        }
                        catch (Exception e)
                        {
                            saveError(e, "import.txt", "date" + time.ToString("yyyyMMdd"));
                            return;
                        }
                    }
                    else if (args.Length == 3)
                    {
                        DateTime start,end;
                        try
                        {
                            start = DateTime.Parse(args[1]);
                            end = DateTime.Parse(args[2]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }
                        DateTime cur = start;
                        while (cur <= end)
                        {
                            try
                            {
                                combiner.execute(cur);
                            }
                            catch (Exception e)
                            {
                                saveError(e, "import.txt", "date" + cur.ToString("yyyyMMdd"));
                            }
                            cur = cur.AddDays(1);
                        }
                    }
                    break;
                #endregion
                
                #region schedule 排班表
                case "schedule":
                    bool forceClear = true;
                    if (args.Length >= 3 && args.Length <= 4)
                    {
                        int year = Convert.ToInt32(args[1]);
                        int month = Convert.ToInt32(args[2]);
                        if (args.Length == 4 && args[3].Trim() == "false")
                            forceClear = false;

                        combiner.importSchedule(year, month, year, month, forceClear);
                    }
                    else if (args.Length >= 5 && args.Length <= 6)
                    {
                        int start_year = Convert.ToInt32(args[1]);
                        int start_month = Convert.ToInt32(args[2]);
                        int end_year = Convert.ToInt32(args[3]);
                        int end_month = Convert.ToInt32(args[4]);
                        if (args.Length == 6 && args[3].Trim() == "false")
                            forceClear = false;
                        combiner.importSchedule(start_year, start_month, end_year, end_month, forceClear);
                    }
                    else
                        Console.WriteLine("参数数目不正确，请重新输入");
                        return;
                    break;
                #endregion

                #region check_schedule 检查排班表
                case "check_schedule":
                    if (args.Length == 3)
                    {
                        int year = Convert.ToInt32(args[1]);
                        int month = Convert.ToInt32(args[2]);
                        CheckScheduleRight(year, month,year,month);
                    }
                    else if (args.Length == 5)
                    {
                        int start_year = Convert.ToInt32(args[1]);
                        int start_month = Convert.ToInt32(args[2]);
                        int end_year = Convert.ToInt32(args[3]);
                        int end_month = Convert.ToInt32(args[4]);
                        CheckScheduleRight(start_year, start_month, end_year, end_month);
                    }
                    else
                        Console.WriteLine("参数数目不正确，请重新输入");
                    return;
                    break;
                #endregion

                #region check_cityfore 检查城镇报数据完整性
                case "check_cityfore":
                    if (args.Length == 2)
                    {
                        DateTime time;
                        try
                        {
                            time = DateTime.Parse(args[1]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }

                        ForeRepository repository = ForeRepositoryFactory.NormalCityForeRepository(ConfigurationManager.AppSettings["ConnectionString"]);
                        BaseForeHealth health = new CityForeHealth(repository);
                        CheckForeRepositoryHealth(health, time, time);
                    }
                    else if (args.Length == 3)
                    {
                        DateTime start, end;
                        try
                        {
                            start = DateTime.Parse(args[1]);
                            end = DateTime.Parse(args[2]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }

                        ForeRepository repository = ForeRepositoryFactory.NormalCityForeRepository(ConfigurationManager.AppSettings["ConnectionString"]);
                        BaseForeHealth health = new CityForeHealth(repository);
                        CheckForeRepositoryHealth(health, start, end);
                    }
                    break;
                #endregion

                #region check_zyt 检查国家局数据完整性
                case "check_zyt":
                    if (args.Length == 2)
                    {
                        DateTime time;
                        try
                        {
                            time = DateTime.Parse(args[1]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }

                        ForeRepository repository = ForeRepositoryFactory.ZytCityForeRepository(ConfigurationManager.AppSettings["ConnectionString"]);
                        BaseForeHealth health = new ZytForeHealth(repository);
                        CheckForeRepositoryHealth(health, time, time);
                    }
                    else if (args.Length == 3)
                    {
                        DateTime start, end;
                        try
                        {
                            start = DateTime.Parse(args[1]);
                            end = DateTime.Parse(args[2]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }

                        ForeRepository repository = ForeRepositoryFactory.ZytCityForeRepository(ConfigurationManager.AppSettings["ConnectionString"]);
                        BaseForeHealth health = new ZytForeHealth(repository);
                        CheckForeRepositoryHealth(health, start, end);
                    }
                    break;
                #endregion

                #region check_sitefore 检查指导报数据完整性
                case "check_sitefore":
                    if (args.Length == 2)
                    {
                        DateTime time;
                        try
                        {
                            time = DateTime.Parse(args[1]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }

                        ForeRepository repository = ForeRepositoryFactory.StSiteForeRepository(ConfigurationManager.AppSettings["ConnectionString"]);
                        BaseForeHealth health = new StSiteForeHealth(repository);
                        CheckForeRepositoryHealth(health, time, time);
                    }
                    else if (args.Length == 3)
                    {
                        DateTime start, end;
                        try
                        {
                            start = DateTime.Parse(args[1]);
                            end = DateTime.Parse(args[2]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }

                        ForeRepository repository = ForeRepositoryFactory.StSiteForeRepository(ConfigurationManager.AppSettings["ConnectionString"]);
                        BaseForeHealth health = new StSiteForeHealth(repository);
                        CheckForeRepositoryHealth(health, start, end);
                    }
                    break;
                #endregion

                #region 人工站实况
                case "manual":
                    if (args.Length == 4)
                    {
                        int year = Convert.ToInt32(args[1]);
                        int month = Convert.ToInt32(args[2]);
                        string reCalSemiString = args[3].Trim();
                        bool reSemi = true;
                        if (reCalSemiString == "true")
                            reSemi = true;
                        else if (reCalSemiString == "false")
                            reSemi = false;
                        combiner.importManualData(year, month, year, month, reSemi);
                    }
                    else if (args.Length == 6)
                    {
                        int start_year = Convert.ToInt32(args[1]);
                        int start_month = Convert.ToInt32(args[2]);
                        int end_year = Convert.ToInt32(args[3]);
                        int end_month = Convert.ToInt32(args[4]);
                        string reCalSemiString = args[5].Trim();
                        bool reSemi = true;
                        if (reCalSemiString == "true")
                            reSemi = true;
                        else if (reCalSemiString == "false")
                            reSemi = false;
                        combiner.importManualData(start_year, start_month, end_year, end_month, reSemi);
                    }
                    else
                        Console.WriteLine("参数数目不正确，请重新输入");
                        return;
                    break;
                #endregion

                #region 自动站实况
                case "auto":
                    if (args.Length == 3)
                    {
                        bool reSemi = true;
                        DateTime time;
                        try
                        {
                            time = DateTime.Parse(args[1]);
                            string reCalSemiString = args[2].Trim();
                            
                            if (reCalSemiString == "true")
                                reSemi = true;
                            else if (reCalSemiString == "false")
                                reSemi = false;
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }
                        try
                        {
                            combiner.importRealData(time, time, reSemi);
                        }
                        catch (Exception e)
                        {
                            Logger.Error(e);
                            return;
                        }
                    }
                    else if (args.Length == 4)
                    {
                        DateTime start, end;
                        bool reSemi = true;
                        try
                        {
                            start = DateTime.Parse(args[1]);
                            end = DateTime.Parse(args[2]);

                            string reCalSemiString = args[3].Trim();

                            if (reCalSemiString == "true")
                                reSemi = true;
                            else if (reCalSemiString == "false")
                                reSemi = false;
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }
                        try
                        {
                            combiner.importRealData(start, end, reSemi);
                        }
                        catch (Exception e)
                        {
                            Logger.Error(e);
                            return;
                        }
                    }
                    break;
                #endregion

                case "clearcache":
                    ClearCache();
                    break;
                case "clearmemcached":
                    ClearMemcache();
                    break;
                case "copy":
                    if (args.Length == 1)
                    {
                        DateTime now = DateTime.Now;
                        CopyDataFileForSingleDate(now);
                    }
                    else if (args.Length == 2)
                    {
                        DateTime time;
                        try
                        {
                            time = DateTime.Parse(args[1]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }
                        try
                        {
                            CopyDataFileForSingleDate(time);
                        }
                        catch (Exception e)
                        {
                            Logger.Error(e);
                            return;
                        }
                    }
                    else if (args.Length == 3)
                    {
                        DateTime start, end;
                        try
                        {
                            start = DateTime.Parse(args[1]);
                            end = DateTime.Parse(args[2]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }
                        try
                        {
                            DateTime cur = start;
                            while (cur <= end)
                            {
                                CopyDataFileForSingleDate(cur);
                                cur = cur.AddDays(1);
                            }
                        }
                        catch (Exception e)
                        {
                            Logger.Error(e);
                            return;
                        }
                    }
                    break;
                case "usersite":                    
                    if (args.Length == 2)
                    {
                        DateTime time;
                        try
                        {
                            time = DateTime.Parse(args[1]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }
                        try
                        {
                            reimportUserSiteFore(time,time);
                        }
                        catch (Exception e)
                        {
                            Logger.Error(e);
                            return;
                        }
                    }
                    else if (args.Length == 3)
                    {
                        DateTime start,end;
                        try
                        {
                            start = DateTime.Parse(args[1]);
                            end = DateTime.Parse(args[2]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }
                        try
                        {
                            reimportUserSiteFore(start, end);
                        }
                        catch (Exception e)
                        {
                            Logger.Error(e);
                            return;
                        }
                    }
                    break;
                case "zyt":
                    if (args.Length == 2)
                    {
                        DateTime time;
                        try
                        {
                            time = DateTime.Parse(args[1]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }
                        try
                        {
                            reimportZytFore(time, time);
                        }
                        catch (Exception e)
                        {
                            Logger.Error(e); 
                            return;
                        }
                    }
                    else if (args.Length == 3)
                    {
                        DateTime start, end;
                        try
                        {
                            start = DateTime.Parse(args[1]);
                            end = DateTime.Parse(args[2]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }
                        try
                        {
                            reimportZytFore(start, end);
                        }
                        catch (Exception e)
                        {
                            Logger.Error(e);
                            return;
                        }
                    }
                    break;
                case "cityfore":
                    if (args.Length == 2)
                    {
                        DateTime time;
                        try
                        {
                            time = DateTime.Parse(args[1]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }
                        try
                        {
                            reimportCityFore(time, time);
                        }
                        catch (Exception e)
                        {
                            Logger.Error(e);
                            return;
                        }
                    }
                    else if (args.Length == 3)
                    {
                        DateTime start, end;
                        try
                        {
                            start = DateTime.Parse(args[1]);
                            end = DateTime.Parse(args[2]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }
                        try
                        {
                            reimportCityFore(start, end);
                        }
                        catch (Exception e)
                        {
                            Logger.Error(e);
                            return;
                        }
                    }
                    break;
                case "sitefore":
                    if (args.Length == 2)
                    {
                        DateTime time;
                        try
                        {
                            time = DateTime.Parse(args[1]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }
                        try
                        {
                            reimportSiteFore(time, time);
                        }
                        catch (Exception e)
                        {
                            Logger.Error(e);
                            return;
                        }
                    }
                    else if (args.Length == 3)
                    {
                        DateTime start, end;
                        try
                        {
                            start = DateTime.Parse(args[1]);
                            end = DateTime.Parse(args[2]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }
                        try
                        {
                            reimportSiteFore(start, end);
                        }
                        catch (Exception e)
                        {
                            Logger.Error(e);
                            return;
                        }
                    }
                    break;
                case "semi":
                    if (args.Length == 2)
                    {
                        DateTime time;
                        try
                        {
                            time = DateTime.Parse(args[1]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }
                        try
                        {
                            reCalculateSemi(time, time); 
                        }
                        catch (Exception e)
                        {
                            Logger.Error(e);
                            return;
                        }
                    }
                    else if (args.Length == 3)
                    {
                        DateTime start,end;
                        try
                        {
                            start = DateTime.Parse(args[1]);
                            end = DateTime.Parse(args[2]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }
                        try
                        {
                            reCalculateSemi(start, end);
                        }
                        catch (Exception e)
                        {
                            Logger.Error(e);
                            return;
                        }
                    }
                    break;

                case "semi_sitefore":
                    if (args.Length == 2)
                    {
                        DateTime time;
                        try
                        {
                            time = DateTime.Parse(args[1]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }
                        try
                        {
                            string dbConnectionString = ConfigurationManager.AppSettings["ConnectionString"];
                            combiner.ReCalSemi(time, time, dbConnectionString, 
                                new List<ForeRepository>() { ForeRepositoryFactory.StSiteForeRepository(dbConnectionString) });
                        }
                        catch (Exception e)
                        {
                            Logger.Error(e);
                            return;
                        }
                    }
                    else if (args.Length == 3)
                    {
                        DateTime start,end;
                        try
                        {
                            start = DateTime.Parse(args[1]);
                            end = DateTime.Parse(args[2]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }
                        try
                        {
                            string dbConnectionString = ConfigurationManager.AppSettings["ConnectionString"];
                            combiner.ReCalSemi(start, end, dbConnectionString,
                                new List<ForeRepository>() { ForeRepositoryFactory.StSiteForeRepository(dbConnectionString) });
                        }
                        catch (Exception e)
                        {
                            Logger.Error(e);
                            return;
                        }
                    }
                    break;
                #region checkoldsemi
                case "checkoldsemi":
                    if (args.Length == 4)
                    {
                        string table = args[1];
                        ForeRepository repository;
                        List<string> valideTables = new List<string> { "site", "city", "zyt" };
                        DateTime date ;
                        if (valideTables.IndexOf(table) == -1)
                        {
                            Console.WriteLine("不是合法表名，表名应当为:" + string.Format(",", valideTables));
                            return;
                        }
                        

                        string strSemitype = args[2];
                        ForeSemiType semitype;
                        if (!Enum.TryParse<ForeSemiType>(strSemitype, out semitype))
                        {
                            Console.WriteLine("您输入的实况类型非法，应当为 Auto 或 Manual !");
                            return;
                        }

                        try
                        {
                            date = DateTime.Parse(args[3]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }

                        CompareSemi(table, semitype, date,date);
                    }
                    else if (args.Length == 5)
                    {
                        string table = args[1];
                        ForeRepository repository;
                        List<string> valideTables = new List<string> { "site", "city", "zyt" };
                        DateTime dateBegin, dateEnd;
                        if (valideTables.IndexOf(table) == -1)
                        {
                            Console.WriteLine("不是合法表名，表名应当为:" + string.Format(",", valideTables));
                            return;
                        }


                        string strSemitype = args[2];
                        ForeSemiType semitype;
                        if (!Enum.TryParse<ForeSemiType>(strSemitype, out semitype))
                        {
                            Console.WriteLine("您输入的实况类型非法，应当为 Auto 或 Manual !");
                            return;
                        }

                        try
                        {
                            dateBegin = DateTime.Parse(args[3]);
                            dateEnd = DateTime.Parse(args[4]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("您输入的日期格式非法，请确认!");
                            return;
                        }

                        CompareSemi(table, semitype, dateBegin, dateEnd);
                    }
                    break;
                #endregion
                #region cal
                case "cal":
                    if (args.Length == 5)
                    {
                        string strSpan = args[1];
                        EstimateHourSpan span;
                        if (!Enum.TryParse<EstimateHourSpan>(strSpan, out span))
                        {
                            Console.WriteLine("您输入的时间段类型非法，应当为 H12 或 H24 !");
                            return;
                        }
                        Console.WriteLine(span);

                        string strSemitype = args[2];
                        ForeSemiType semitype;
                        if (!Enum.TryParse<ForeSemiType>(strSemitype, out semitype))
                        {
                            Console.WriteLine("您输入的实况类型非法，应当为 Auto 或 Manual !");
                            return;
                        }

                        float real = Convert.ToSingle(args[3]);
                        int fore = Convert.ToInt32(args[4]);

                        System.Console.WriteLine("分级降水检验 " + Calculate.PrecipitationLevelInspection(Calculate.RealValue2PrecipitationLevel(span, WaterfallKind.Rain, real, semitype), fore));
                        System.Console.WriteLine("晴雨(雪)检验 "+Calculate.WaterfallAmountInspection(Calculate.RealValue2WaterfallAmount(real, semitype), fore));
                        System.Console.WriteLine("一般性降水检验 "+Calculate.WaterfallLevelInspection(Calculate.RealValue2WaterfallLevel(span, WaterfallKind.Rain, real, semitype), fore).ToString());
                        System.Console.WriteLine("累加降水量检验 "+Calculate.SumPrecipitationLevelInspection(Calculate.RealValue2SumPrecipitationLevel(real, semitype), fore).ToString());
                        
                    }
                    break;
                #endregion
                default:
                    Console.WriteLine("找不到指令的命令");
                    printMenu();
                    break;

                
            }
        }

        private static void reimportSiteFore(DateTime start, DateTime end)
        {
            DataImporterCombiner importer = new DataImporterCombiner(ConfigurationManager.AppSettings);

            importer.CompleteSiteFore(start, end);
        }

        private static void reimportCityFore(DateTime start, DateTime end)
        {
            DataImporterCombiner importer = new DataImporterCombiner(ConfigurationManager.AppSettings);

            importer.CompleteCityFore(start, end);
        }

        private static void reimportZytFore(DateTime start, DateTime end)
        {
            DataImporterCombiner importer = new DataImporterCombiner(ConfigurationManager.AppSettings);

            importer.CompleteZytFore(start, end);
        }

        static void saveError(Exception e, string file, string content)
        {
            FileStream fs = new FileStream(file, FileMode.Append);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(content);
            sw.WriteLine(e.Message);
            sw.WriteLine("");
            sw.Flush();
            sw.Close();
        }

        static void printMenu()
        {
            Console.WriteLine("******************************************************************");
            Console.WriteLine("日期符号 day: 格式  yyyy-mm-dd ，如：2012-10-10");
            Console.WriteLine("_____________import 导入预报、实况数据________________");
            Console.WriteLine("import day  导入day这一天的数据");
            Console.WriteLine("import day1 day2 导入 day1 至 day2 的数据");
            Console.WriteLine("_____________schedule 导入排班表___  boolean 表示是否清空原先的数据，可选。默认false _____________");
            Console.WriteLine("schedule year month {boolean} 如： schedule 2012 5 true ");
            Console.WriteLine("schedule start_year start_month end_year end_month 如： schedule 2012 5 2012 6  true");           
            Console.WriteLine("_____________manual 导入人工站实况________________");
            Console.WriteLine("manual year month reSemi如： manual 2012 5 true, 表示导入2012年5月的数据并重算semi");
            Console.WriteLine("manual year month reSemi如： manual 2012 5 false, 表示导入2012年5月的数据但是不重算semi");
            Console.WriteLine("manual start_year start_month end_year end_month reSemi如： manual 2012 5 2012 6 true");
            Console.WriteLine("manual start_year start_month end_year end_month reSemi如： manual 2012 5 2012 6 false");
            Console.WriteLine("_____________auto 导入自动站实况________________");
            Console.WriteLine("auto day reSemi 导入day这一天的实况数据, reSemi决定是否重算semi");
            Console.WriteLine("auto day1 day2 reSemi 导入 day1 至 day2 的自动站实况数据，reSemi决定是否重算semi");
            Console.WriteLine("_____________clearcache 清空缓冲表________________");
            Console.WriteLine("clearcache ");
            Console.WriteLine("_____________copy 拷贝数据文件________________");
            Console.WriteLine("copy day 如： copy 2012-10-12 ");
            Console.WriteLine("copy day1 day2 拷贝 day1 至 day2 的数据, 如 copy 2012-10-12 2012-10-30");
            Console.WriteLine("_____________check_schedule 检查排班表数据是否完整________________");
            Console.WriteLine("check_schedule year month 如： schedule 2012 5 ");
            Console.WriteLine("check_schedule start_year start_month end_year end_month 如： schedule 2012 5 2012 6");
            Console.WriteLine("_____________check_cityfore 检测城镇报数据的错误________________");
            Console.WriteLine("check_cityfore day  检测城镇报day这一天的数据");
            Console.WriteLine("check_cityfore day1 day2 检测城镇报day1 至 day2 的数据");
            Console.WriteLine("_____________check_zyt 检测国家局数据的错误________________");
            Console.WriteLine("check_zyt day  检测国家局day这一天的数据");
            Console.WriteLine("check_zyt day1 day2 检测国家局day1 至 day2 的数据");
            Console.WriteLine("_____________usersite 重新入库用户指导站数据_________");
            Console.WriteLine("usersite day 如： usersite 2012-10-12 ");
            Console.WriteLine("usersite day1 day2 拷贝 day1 至 day2 的数据, 如 usersite 2012-10-12 2012-10-30");
            Console.WriteLine("_____________zyt 重新入库国家局数据_________");
            Console.WriteLine("zyt day 如： zyt 2012-10-12 ");
            Console.WriteLine("zyt day1 day2 拷贝 day1 至 day2 的数据, 如 zyt 2012-10-12 2012-10-30");
            Console.WriteLine("_____________cityfore 重新入库城镇报数据_________");
            Console.WriteLine("cityfore day 如： cityfore 2012-10-12 ");
            Console.WriteLine("cityfore day1 day2 拷贝 day1 至 day2 的数据, 如 cityfore 2012-10-12 2012-10-30");
            Console.WriteLine("_____________sitefore 重新入库指导报数据_________");
            Console.WriteLine("sitefore day 如： sitefore 2012-10-12 ");
            Console.WriteLine("sitefore day1 day2 拷贝 day1 至 day2 的数据, 如 sitefore 2012-10-12 2012-10-30");
            Console.WriteLine("_____________semi 重新计算指定日期区间的semi字符串_________");
            Console.WriteLine("semi day 如： semi 2012-10-12 ");
            Console.WriteLine("semi day1 day2 拷贝 day1 至 day2 的数据, 如 semi 2012-10-12 2012-10-30");
            Console.WriteLine("_____________semi_sitefore 重新计算指定日期区间的指导站的semi字符串_________");
            Console.WriteLine("semi_sitefore day 如： semi_sitefore 2012-10-12 ");
            Console.WriteLine("semi_sitefore day1 day2 拷贝 day1 至 day2 的数据, 如 semi_sitefore 2012-10-12 2012-10-30");
            Console.WriteLine("_____________checkoldsemi 与旧数据库中的semi做比较_________");
            Console.WriteLine("checkoldsemi day 如： checkoldsemi city 2012-10-12 Auto ");
            Console.WriteLine("checkoldsemi day 如： checkoldsemi site 2012-10-12 Auto ");
            Console.WriteLine("checkoldsemi day 如： checkoldsemi zyt 2012-10-12 Auto ");
            Console.WriteLine("_____________cal 指定类型，计算semi结果_________");
            Console.WriteLine("cal span semitype real fore 如： cal H12 Auto 0 1 ");
            Console.WriteLine("_____________clearmemcached 清空memcache缓存_________");
            Console.WriteLine("clearmemcached");
            Console.WriteLine("******************************************************************");
        }


        /// <summary>
        /// 初始化表结构
        /// </summary>
        private static void ClearCache()
        {
            string connectionString = ConfigurationManager.AppSettings["ConnectionString"];
            IndividualRankRepository individualRepository = new IndividualRankRepository(connectionString);
            if (!individualRepository.IsTableExist())
                individualRepository.CreateTable();
            individualRepository.ClearTable();
            Console.WriteLine("IndividualRank cleared");


            ZytRankRepository zytRepository = new ZytRankRepository(connectionString);
            if (!zytRepository.IsTableExist())
                zytRepository.CreateTable();
            zytRepository.ClearTable();
            Console.WriteLine("ZytRank cleared");

            CollectionRankRepository collectRepository = new CollectionRankRepository(connectionString);
            if (!collectRepository.IsTableExist())
                collectRepository.CreateTable();
            collectRepository.ClearTable();
            Console.WriteLine("CollectionRank cleared");

            StationMatchRepository stationMatchRepository = new StationMatchRepository(connectionString);
            if (!stationMatchRepository.IsTableExist())
                stationMatchRepository.CreateTable();
            Console.WriteLine("StationMatch cleared");

            MonthScoreRepository repository = new MonthScoreRepository(connectionString);
            if (!repository.IsTableExist())
                repository.CreateTable();
            repository.ClearTable();
            Console.WriteLine("MonthScore cleared");

            StandardMonthScoreRepository repository1 = new StandardMonthScoreRepository(connectionString);
            if (!repository1.IsTableExist())
                repository1.CreateTable();
            repository1.ClearTable();
            Console.WriteLine("StandardMonthScore cleared");

            ZytMonthScoreRepository repository2 = new ZytMonthScoreRepository(connectionString);
            if (!repository2.IsTableExist())
                repository2.CreateTable();
            repository2.ClearTable();
            Console.WriteLine("ZytMonthScore cleared");
            

            IndividualGroupScoreRepository individualRepository1 = new IndividualGroupScoreRepository(connectionString);
            if (!individualRepository1.IsTableExist())
                individualRepository1.CreateTable();
            individualRepository1.ClearTable();
            Console.WriteLine("IndividualGroupScore cleared");

            ForeRealCompareRepository compareRepository = new ForeRealCompareRepository(connectionString);
            if (!compareRepository.IsTableExist())
                compareRepository.CreateTable();
            compareRepository.ClearTable();
            Console.WriteLine("ForeRealCompare cleared");

            IndividualScoreRepository individualScoreRepository = new IndividualScoreRepository(connectionString);
            if (!individualScoreRepository.IsTableExist())
                individualScoreRepository.CreateTable();
            individualScoreRepository.ClearTable();
            Console.WriteLine("IndividualScore cleared");

            IndividualSiteForeScoreRepository individualSiteForeRepository = new IndividualSiteForeScoreRepository(connectionString);
            if (!individualSiteForeRepository.IsTableExist())
                individualSiteForeRepository.CreateTable();
            individualSiteForeRepository.ClearTable();
            Console.WriteLine("IndividualSiteForeScore cleared");

            IndividualSiteForeRankRepository individualSiteForeRankRepository = new IndividualSiteForeRankRepository(connectionString);
            if (!individualSiteForeRankRepository.IsTableExist())
                individualSiteForeRankRepository.CreateTable();
            individualSiteForeRankRepository.ClearTable();
            Console.WriteLine("IndividualSiteForeRank cleared");

        }

        /// <summary>
        /// 将某一天的实况数据从远端拷贝至本机
        /// </summary>
        /// <param name="dt"></param>
        private static void CopyDataFileForSingleDate(DateTime dt)
        {
            string[] pathList = null;
            IDataFileFinder finder;
            BaseDataFileCopyer copyer;

            string prefix = "";
            //远端机器上的 Normal_CityFore,RainFore,SiteFore数据会在第二天打包
            if (dt.Date.CompareTo(DateTime.Now.Date) == 0)
            {
                prefix = "Today_";
            }
            
            //城镇报、降水等值线、指导站过了当天后，数据都会备份至另外一个目录。所以当天的目录不同于往日的目录
            System.Console.Write("拷贝 CityFore 文件 ");
            
            finder = new NormalCityForeFinder();
            pathList = finder.GetFileFromDirectory(dt, ConfigurationManager.AppSettings[prefix + "CityForeDirectory"]);
            System.Console.WriteLine("发现文件" + pathList.Length.ToString() + "个");
            copyer = DataFileCopyerFactory.NormalCityForeCopyer(ConfigurationManager.AppSettings["Copy_Directory_Root"] + ConfigurationManager.AppSettings["Copy_CityForeDirectory"]);
            copyer.copyFiles(pathList);
            

            System.Console.Write("拷贝 RainFore 文件 ");
            finder = new RainForeFinder();
            pathList = finder.GetFileFromDirectory(dt, ConfigurationManager.AppSettings[prefix + "RainForeDirectory_ZhongQi"]);
            System.Console.Write("发现中期文件" + pathList.Length.ToString() + "个,");
            copyer = DataFileCopyerFactory.RainForeCopyer(ConfigurationManager.AppSettings["Copy_Directory_Root"] + ConfigurationManager.AppSettings["Copy_RainForeDirectory_ZhongQi"]);
            copyer.copyFiles(pathList);
            pathList = finder.GetFileFromDirectory(dt, ConfigurationManager.AppSettings[prefix + "RainForeDirectory_DuanQi"]);
            System.Console.WriteLine("发现短期文件" + pathList.Length.ToString() + "个,");
            copyer = DataFileCopyerFactory.RainForeCopyer(ConfigurationManager.AppSettings["Copy_Directory_Root"] + ConfigurationManager.AppSettings["Copy_RainForeDirectory_DuanQi"]);
            copyer.copyFiles(pathList);

            System.Console.Write("拷贝 SiteFore 文件 ");
            finder = new SiteForeFinder();
            pathList = finder.GetFileFromDirectory(dt, ConfigurationManager.AppSettings[prefix + "StSiteForeDirectory"]);
            System.Console.Write("发现短期文件" + pathList.Length.ToString() + "个,");
            copyer = DataFileCopyerFactory.SiteForeCopyer(ConfigurationManager.AppSettings["Copy_Directory_Root"] + ConfigurationManager.AppSettings["Copy_StSiteForeDirectory"]);
            copyer.copyFiles(pathList);
            pathList = finder.GetFileFromDirectory(dt, ConfigurationManager.AppSettings[prefix + "StSiteForeDirectory_Zhongqi"]);
            System.Console.WriteLine("发现中期文件" + pathList.Length.ToString() + "个,");
            copyer = DataFileCopyerFactory.SiteForeCopyer(ConfigurationManager.AppSettings["Copy_Directory_Root"] + ConfigurationManager.AppSettings["Copy_StSiteForeDirectory_Zhongqi"]);
            copyer.copyFiles(pathList);
            

            System.Console.Write("拷贝 Zyt 文件 ");
            finder = new ZytCityForeFinder();
            pathList = finder.GetFileFromDirectory(dt, ConfigurationManager.AppSettings["ZytCityForeDirectory"]);
            System.Console.WriteLine("发现文件" + pathList.Length.ToString() + "个,");
            copyer = DataFileCopyerFactory.ZytCityForeCopyer(ConfigurationManager.AppSettings["Copy_Directory_Root"] + ConfigurationManager.AppSettings["Copy_ZytCityForeDirectory"]);
            copyer.copyFiles(pathList);

            System.Console.Write("拷贝 User SiteFore 文件 ");
            finder = new UserSiteForeFinder();
            pathList = finder.GetFileFromDirectory(dt, ConfigurationManager.AppSettings["UserSiteForeDirectory"]);
            System.Console.WriteLine("发现文件" + pathList.Length.ToString() + "个,");
            copyer = DataFileCopyerFactory.UserSiteForeCopyer(ConfigurationManager.AppSettings["Copy_Directory_Root"] + ConfigurationManager.AppSettings["Copy_UserSiteForeDirectory"]);
            copyer.copyFiles(pathList);

            System.Console.Write("拷贝 AutoReal 文件 ");
            finder = new AutoStationFinder();
            pathList = finder.GetFileFromDirectory(dt, ConfigurationManager.AppSettings["AutoStationDirectory"]);
            System.Console.WriteLine("发现文件" + pathList.Length.ToString() + "个,");
            copyer = DataFileCopyerFactory.AutoStationCopyer(ConfigurationManager.AppSettings["Copy_Directory_Root"] + ConfigurationManager.AppSettings["Copy_AutoStationDirectory"]);
            copyer.copyFiles(pathList);
            System.Console.WriteLine("");

            if (dt.Day == Convert.ToInt32(ConfigurationManager.AppSettings["ManualImportDate"] ))
            {
                System.Console.Write("符合配置指定的日期 " + ConfigurationManager.AppSettings["ManualImportDate"] + " ,拷贝 ManaulReal 文件 ");
                finder = new ManualStationFinder();
                pathList = finder.GetFileFromDirectory(dt, ConfigurationManager.AppSettings["ManualStationDirectory"]);
                System.Console.WriteLine("发现文件" + pathList.Length.ToString() + "个,");
                copyer = DataFileCopyerFactory.ManualStationCopyer(ConfigurationManager.AppSettings["Copy_Directory_Root"] + ConfigurationManager.AppSettings["Copy_ManualStationDirectory"]);
                copyer.copyFiles(pathList);
                System.Console.WriteLine("");
            }
        }

        private static void reimportUserSiteFore(DateTime start, DateTime end)
        {
            DataImporterCombiner importer = new DataImporterCombiner( ConfigurationManager.AppSettings );

            importer.CompleteSiteForeLackFile(start, end, true);
        }

        private static void reCalculateSemi(DateTime start, DateTime end)
        {
            DataImporterCombiner combiner = new DataImporterCombiner(ConfigurationManager.AppSettings);
            string connectionString = ConfigurationManager.AppSettings["ConnectionString"];
            combiner.ReCalSemi(start, end, connectionString);
        }

        private static void  ClearMemcache()
        {
            MemcachedClient.Setup("MyCache", ConfigurationManager.AppSettings["Memcached_Servers"].Split(new char[] { ',' } ));
            MemcachedClient cache = MemcachedClient.GetInstance("MyCache");
            cache.SendReceiveTimeout = 5000;
            cache.ConnectTimeout = 5000;
            cache.MinPoolSize = 1;
            cache.MaxPoolSize = 10;
            cache.FlushAll();

        }

        private static void CheckScheduleRight(int startYear, int startMonth, int endYear, int endMonth)
        {
            string connectionString = ConfigurationManager.AppSettings["ConnectionString"];

            DateTime start = new DateTime(startYear, startMonth, 1);
            DateTime end = new DateTime(endYear, endMonth, 1).AddMonths(1).AddDays(-1) ;
            IDataFileFinder finder = new ScheduleFinder();

            AffiliationRepository affiliationRepository = new AffiliationRepository(connectionString);
            AffiliationEntity[] affiliations = affiliationRepository.GetStationLevel(5);

            ScheduleHealth healthChecker = new ScheduleHealth(connectionString);
            DateTime cur = start;


            while (cur <= end)
            {

                foreach (AffiliationEntity entity in affiliations)
                {
                    if (entity.code == "00001")
                        continue;
                    healthChecker.IsHealth(cur, entity.code);                    
                }

                cur = cur.AddDays(1);
            }
        }

        //private static void CheckForeRepositoryHealth(BaseForeHealth health ,DateTime beginDate, DateTime endDate)
        //{                          
        //    //health.IsHealth(beginDate, endDate);            
        //}

        private static void CompareSemi(string table, ForeSemiType semitype, DateTime beginDate, DateTime endDate)
        {
            string oldConnectionString = ConfigurationManager.AppSettings["OldConnectionString"];
            string connectionString = ConfigurationManager.AppSettings["ConnectionString"];
            ForeRepository repository = ForeRepositoryFactory.NormalCityForeRepository(connectionString); 
            switch (table)
            {
                case "site":
                    repository = ForeRepositoryFactory.StSiteForeRepository(connectionString);
                    break;
                case "city":
                    repository = ForeRepositoryFactory.NormalCityForeRepository(connectionString);
                    break;
                case "zyt":
                    repository = ForeRepositoryFactory.ZytCityForeRepository(connectionString);
                    break;

            }

            DateTime curDateTime = beginDate;
            while (curDateTime <= endDate)
            {
                EstimateChecker.CheckDayForeRecord(oldConnectionString, repository, curDateTime, semitype);
                curDateTime = curDateTime.AddDays(1);
            }
            
        }
    }
}
